package com.ckzp.jfinal.system.controller;

import cn.hutool.core.util.DesensitizedUtil;
import com.ckzp.core.ConfigUtil;
import com.ckzp.core.Results;
import com.ckzp.core.id.UUIDHex;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.lc.Aes;
import com.ckzp.core.util.HtmlUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.base.PageSearch;
import com.ckzp.jfinal.plugins.trans.TransData;
import com.ckzp.jfinal.system.WebSite;
import com.ckzp.jfinal.system.cache.*;
import com.ckzp.jfinal.system.model.SysActivity;
import com.ckzp.jfinal.system.model.SysMenu;
import com.ckzp.jfinal.system.util.SysMenuUtil;
import com.ckzp.jfinal.system.util.SysUserUtil;
import com.ckzp.jfinal.system.validate.SysUserValidator;
import com.ckzp.plugins.layui.LayuiData;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.core.lc.Md5;
import com.ckzp.core.model.Datas;
import com.ckzp.jfinal.base.BaseController;
import com.ckzp.jfinal.interceptor.Admins;
import com.ckzp.jfinal.form.FormData;
import com.ckzp.jfinal.form.FormSelect;
import com.ckzp.jfinal.interceptor.Roles;
import com.ckzp.jfinal.system.model.SysRole;
import com.ckzp.jfinal.system.model.SysUser;
import com.ckzp.jfinal.system.util.LoginUtil;
import com.ckzp.weixin.WxTool;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 51594 on 2019/10/12.
 */
public class SysUserController extends BaseController {

    public void index() {
        renderText("系统用户管理");
    }

    /**
     * 用户列表
     */
    @Admins(roles = "system", name = "系统用户列表", log = false)
    public void UserList() {
        String defaultpwd = SysConfigCache.getConfigValue("defaultpwd");
        FormData fd = FormData.dao();
        setAttr("form", fd.setKey(String.valueOf(defaultpwd)));
        render("UserList.html");
    }

    /**
     * 用户列表
     */
    @Admins(roles = "system", name = "系统用户列表", log = false)
    public void UserMenuActivityList() {
        int emp_id = getParaInt("emp_id", 0);
        FormData fd = SysMenuUtil.n().getUserMenuAuthorTreeData(emp_id);
        fd.addData("emp_id", emp_id);
        fd.addData("roles", SysRoleCache.transRoleName(SysUserUtil.n().getUserRoleString(emp_id)));
        fd.addData("username", SysUserCache.transUserName(emp_id));
        //反回前端
        setForm(fd.setKey(emp_id));
        setAttr("form", fd);
        render("UserMenuActivityList.html");
    }


    /**
     * 查询菜单活动Api
     */
    @Admins(roles = "system", name = "查询菜单活动Api", log = false)
    public void UserMenuActivityListDataApi() {
        int menu_id = getParaInt("menu_id", 0);
        int emp_id = getParaInt("emp_id", 0);
        String user_role = SysUserUtil.n().getUserRoleString(emp_id);
        String sql = "from sys_activity a,sys_menu_activity ma where ma.act_id=a.act_id and ma.menu_id=?";
        PageSearch ps = PageSearch.n().setSql(sql).setSelect("select a.*").addValue(menu_id).init(getRequest());
        ps.orderby("a.sindex");
        Page<SysActivity> pages = ps.paginate(SysActivity.dao);
        List<SysActivity> datalist = pages.getList();
        for (SysActivity activity : datalist) {
            activity.put("roles", SysRoleCache.transRoleName(activity.mod.getStr("act_role")));
            if (SysMenuUtil.n().hasRole(user_role, activity.mod.getStr("act_role"))) {
                activity.put("has_role", "允许").put("has_role_color", "green");
            } else {
                activity.put("has_role", "无权限").put("has_role_color", "red");
            }
        }
        renderJson(LayuiData.newData().setData(datalist).setCount(pages.getTotalRow()));
    }

    /**
     * 修改用户信息页面
     */
    @Admins(roles = "login", name = "修改用户信息页面", log = false)
    public void EditMyInfo() {
        int emp_id = getEmpID();
        SysUser su = SysUser.dao.findById(emp_id);
        if (su == null) {
            renderText("您未登陆");
        }
        /////////////////////
        FormSelect dept = FormSelect.n().setSource("select dept_id as id,dept_name as name from sys_department");
        dept.setCanNull(true);
        dept.setName("dept_id");
        dept.setLayVerify("dept_id");
        dept.setReadOnly(true);

        setForm(FormData.dao().setActions("EDIT").addSelect("deptid", dept.showHtml(su.getStr("dept_id"))));
        setAttr("user", su);
        render("EditMyInfo.html");
    }

    /**
     * 修改用户信息API
     */
    @Admins(roles = "login", name = "修改用户信息API", log = true)
    public void ModifyMyInfoApi() {
        int emp_id = getEmpID();
        SysUser su = SysUser.dao.findById(emp_id);
        if (su == null) {
            renderJson(Json(false, "您未登陆"));
        } else {
            Datas datas = getDatas(getPara("postdata"));
            boolean results = SysUser.dao.findById(emp_id)
                    .set("login_id", getStr(datas, "login_id"))
                    .set("user_name", getStr(datas, "user_name"))
                            //.set("dept_id", getStr(datas, "dept_id"))
                    .set("user_email", getStr(datas, "user_email"))
                    .set("user_phone", getStr(datas, "user_phone"))
                    .update();
            renderJson(Json(results, MSG_EDIT));
        }
    }

    /**
     * 添加用户页面
     */
    @Admins(roles = "system", name = "添加用户页面", log = true)
    public void AddSystemUser() {
        FormSelect dept = FormSelect.n().setSource("select dept_id as id,dept_name as name from sys_department");
        dept.setCanNull(true);
        dept.setName("dept_id");
        //dept.setLayVerify("dept_id");

        FormData fd = FormData.dao().setActions("ADD");
        fd.addSelect("deptid", dept.showHtml(""));
        fd.addSelect("usertype", SysTypeCache.getFormSelect("sys_user_type", false).setName("user_type").setCanNull(false).showHtml(""));

        setAttr("user", new SysUser());
        setAttr("form", fd);

        render("ModifySystemUser.html");
    }

    /**
     * 修改用户页面
     */
    @Admins(roles = "system", name = "修改用户页面", log = false)
    public void EditSystemUser() {
        int emp_id = getParaToInt("emp_id");
        SysUser su = SysUser.dao.findById(emp_id);

        FormData fd = FormData.dao().setActions("EDIT");

        /////////////////////
        if (su.getStr("user_post") != null) su.put("user_posts", "[" + SysUserUtil.unTransPost(su.mod.getStr("user_post", "")) + "]");
        FormSelect dept = FormSelect.n();
        dept.setSource("select dept_id as id,dept_name as name from sys_department");
        dept.setCanNull(true);
        dept.setName("dept_id");

        fd.addSelect("deptid", dept.showHtml(su.getStr("dept_id")));
        fd.addSelect("usertype", SysTypeCache.getFormSelect("sys_user_type", false).setName("user_type").setCanNull(false).showHtml(su.getStr("user_type")));

        setForm(fd);
        setAttr("user", su);
        render("ModifySystemUser.html");
    }

    /**
     * 编辑用户资料API
     */
    @Admins(roles = "system", name = "编辑用户资料API", log = true)
    @Before(SysUserValidator.class)
    public void ModifySystemUserApi() {
        Datas datas = getDatas();
        int emp_id = datas.getInt("emp_id", 0);
        String defaultpwd = SysConfigCache.getConfigValue("defaultpwd");
        if (emp_id > 0) {//更新
            boolean results = SysUser.dao.findById(emp_id)
                    .set("emp_id", datas.getInt("emp_id"))
                    .set("login_id", datas.getStr("login_id"))
                    .set("user_name", datas.getStr("user_name"))
                    .set("dept_id", datas.getStr("dept_id"))
                    .set("dept_name", SysDeptCache.transDeptName(datas.getStr("dept_id")))
                    .set("user_email", datas.getStr("user_email"))
                    .set("user_phone", datas.getStr("user_phone"))
                    .set("user_type", datas.getInt("user_type"))
                    .set("user_post", SysUserUtil.transPost(datas.getStr("user_post")))
                    .set("user_desc", datas.getStr("user_desc"))
                    .update();
            renderJson(Json(results, MSG_EDIT));
        } else {//添加
            boolean results = new SysUser()
                    .set("login_id", datas.getStr("login_id"))
                    .set("user_name", datas.getStr("user_name"))
                    .set("user_pwd", Md5.MD5(defaultpwd))
                    .set("dept_id", datas.getStr("dept_id"))
                    .set("dept_name", SysDeptCache.transDeptName(datas.getStr("dept_id")))
                    .set("user_email", datas.getStr("user_email"))
                    .set("user_phone", datas.getStr("user_phone"))
                    .set("user_post", SysUserUtil.transPost(datas.getStr("user_post")))
                    .set("user_type", datas.getInt("user_type"))
                    .set("user_desc", datas.getStr("user_desc"))
                    .save();
            renderJson(Json(results, MSG_ADD));
        }
    }


    /**
     * 重置用户密码Api
     */
    @Admins(roles = "system", name = "重置用户密码Api", log = true)
    public void ResetPwdApi() {
        String defaultpwd = SysConfigCache.getConfigValue("defaultpwd");

        boolean results = SysUser.dao.findById(getParaToInt("emp_id"))
                .set("user_pwd", Md5.MD5(defaultpwd))
                .update();
        renderJson(Json(results, "密码重置"));
    }

    /**
     * 设置用户角色
     */
    @Admins(roles = "system", name = "设置用户角色页面", log = false)
    public void SetUserRole() {
        int emp_id = getParaToInt("emp_id", 0);
        //取得个人拥有的角色
        List<SysRole> userrolelist = SysRole.dao.find("select role_id from sys_user_role where emp_id=?", emp_id);
        List myrelist = new ArrayList();
        for (int k = 0; k < userrolelist.size(); k++) {
            SysRole role = userrolelist.get(k);
            myrelist.add(role.getStr("role_id"));
        }
        //取得系统所有角色
        List<SysRole> rolelist = SysRole.dao.findAll();
        List relist = new ArrayList();
        for (int k = 0; k < rolelist.size(); k++) {
            SysRole role = rolelist.get(k);
            TransData td = new TransData();
            td.setValue(role.getStr("role_id"));
            td.setTitle(role.getStr("role_name") + "(" + role.getStr("role_id") + ")");
            relist.add(td);
        }
        set("empid", emp_id);
        set("rolestr", toJsonStr(relist));
        set("myrolestr", toJsonStr(myrelist));
        render("SetUserRoles.html");
    }

    /**
     * 设置用户角色api
     */
    @Admins(roles = "system", name = "设置用户角色api", log = true)
    public void SetUserRoleApi() {
        int emp_id = getParaToInt("emp_id", 0);
        String json_rolestr = getPara("role_str");
        List list = JsonUtil.json2List(json_rolestr, TransData.class);
        Db.update("delete from sys_user_role where emp_id=?", emp_id);
        for (int k = 0; k < list.size(); k++) {
            TransData td = (TransData) list.get(k);
            String role = td.getValue();
            if (role != null && role.length() > 0) {
                Db.save("sys_user_role", new Record().set("role_id", role).set("emp_id", emp_id));
            }
        }
        renderJson(JsonResult.n(0, "角色设置成功"));
    }

    /**
     * 检查登陆ID是否存在
     */
    @Admins(roles = "login", name = "检查登陆ID是否存在Api", log = false)
    public void CheckLoginidApi() {
        int emp_id = getParaToInt("emp_id", 0);
        String sql = "select login_id from sys_user where login_id=?";
        if (emp_id > 0) {
            sql = "select login_id from sys_user where emp_id!=" + emp_id + " and login_id=?";
        }
        SysUser user = SysUser.dao.findFirst(sql, getParaStr("login_id", ""));
        if (user == null) {
            renderJson(JsonResult.n(0, "帐号不存在"));
        } else {
            renderJson(JsonResult.n(9, "帐号已存在"));
        }
    }

    /**
     * 用户信息列表API
     */
    @Admins(roles = "system", name = "用户信息列表API", log = false)
    public void SysUserListApi() {
        //////////////////
        PageSearch ps = PageSearch.n().setTable("sys_user").init(getRequest());
        ps.search("del_tag", 0);
        String defaultpwd = SysConfigCache.getConfigValue("defaultpwd");
        FormSelect dept = new FormSelect();
        dept.setSource("select dept_id as id,dept_name as name from sys_department");
        dept.setReadOnly(true);
        FormSelect usertype = SysTypeCache.getFormSelect("sys_user_type", true);
        Page<SysUser> pages = ps.paginate(SysUser.dao);
        List datalist = pages.getList();
        for (int k = 0; k < datalist.size(); k++) {
            SysUser su = (SysUser) datalist.get(k);
            su.put("dept_name", dept.showHtml(su.getStr("dept_id")));
            su.put("user_type_name", usertype.showHtml(su.mod.getInt("user_type")));
            su.put("user_posts", SysPostCache.transPostName(su.mod.getStr("user_post")));
            su.put("pwd", Md5.MD5(defaultpwd).equals(su.get("user_pwd")) ? "默认" : "");
            su.put("user_phone", DesensitizedUtil.mobilePhone(su.getStr("user_phone")));
            su.put("user_email", DesensitizedUtil.email(su.getStr("user_email")));
        }
        renderJson(LayuiData.newData().setCount(pages.getTotalRow()).setData(datalist));
    }

    /**
     * 锁定用户
     */
    @Admins(roles = "system", name = "锁定用户API", log = false)
    public void LockUserApi() {
        renderJson(DoBasePub(SysUser.dao, getParaStr("emp_id", ""), "lock_tag", ""));
    }

    /**
     * 删除用户API
     */
    @Admins(roles = "system", name = "删除用户API", log = true)
    public void DelSystemUserApi() {
        SysUser su = SysUser.dao.findById(getParaToInt("emp_id", 0));
        su.set("del_tag", 1).set("lock_tag", 1).update();
        renderJson(JsonResult.n(0, "删除成功"));
    }

    /**
     * 模拟用户登陆
     * 只有超级用户 administrator 才有这个权限
     */
    @Admins(roles = "administrator", name = "模拟用户登陆", log = true)
    public void InitUserByRole() {
        int emp_id = getParaInt("emp_id", 0);
        if (emp_id == 0) {
            renderText("用户ID不存在");
        } else {
            JsonResult jr = LoginUtil.getInstance().validateUserJwt(emp_id);
            if (jr.getCode() == 0) {
                String jwt = jr.getExtra();
                WebSite.setJwt(getResponse(), jwt);
                getRequest().getSession().setAttribute("VALIDATECODE", null);
                redirect(ConfigUtil.getFullWebAdminPath() + "/index");
            } else {
                renderText(jr.getMsg());
            }
        }
    }

    /**
     * 微信帐号绑定
     */
    @Admins(roles = "login", name = "微信帐号绑定", log = false)
    public void BindWxAccountApi() {
        String uuid = String.valueOf(new Date().getTime());
        Results result = WxTool.getWxQrCodeUrl(Jmode.n().set("type", "web_bind").set("wx_uuid", uuid).set("emp_id", getEmpID()).toJson()).setKeystring(uuid);
        renderJson(result);
    }


    /**
     * 微信帐号绑定
     */
    @Admins(roles = "login", name = "微信帐号绑定", log = false)
    public void getBindWxStatusApi() {
        SysUser user = SysUser.dao.findById(getEmpID());
        if (user.getStr("wx_openid") != null && getParaStr("wx_uuid", "").equals(user.getStr("wx_uuid"))) {
            renderJson(Results.n().setCode(9).setMsg(user.getStr("wx_openid")));
            return;
        }
        renderJson(Results.n());
    }

    /**
     * 取得岗位列表
     */
    @Admins(roles = "system", name = "取得岗位列表", log = true)
    public void getUserPostApi() {
        renderJson(Jmode.n().set("key", 2).set("data", SysUserUtil.n().getSysPostList()));
    }
}
